#ifndef DATASERVERS_H
#define DATASERVERS_H

#include <QObject>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <mutex>
#include <utility>

class DataServers : public QObject
{
private:
    static DataServers* instance;
    DataServers(){}
    Q_OBJECT
public:

    static DataServers* getInstance(){
        return instance;
    }

    ~DataServers(){
        close();
    }

    explicit DataServers(const QString&dbname, QObject *parent = 0);

    DataServers& operator=(const DataServers& other) = delete;

    bool load(const QString&dbname);
    void close(){
        if(db.open ())
            db.close ();
    }

    QStringList getTablesName(){
        if(!db.isValid ())
            return {};
        return db.tables ();
    }

    std::pair<QSqlQuery, bool> query(const QString& sql);
    QSqlQuery getQueryObj()
    {
        return db.exec ();
    }

    bool transaction(){
        m.lock ();
        bool result = db.transaction ();
        if(!result)
            m.unlock ();
        return result;
    }
    bool commit(){
        bool result = db.commit ();
        m.unlock ();
        return result;
    }
    bool rollback(){
        return db.rollback ();
    }

signals:

public slots:


private:
    QString dbName;
    QSqlDatabase db;
    std::mutex m;

    bool connect(const QString &dbname)
    {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(dbname);
        if (!db.open()) {
            qDebug() << "Database Error!";
            return false;
        }
        dbName = dbname;
        return true;
    }
};

#endif // DATASERVERS_H
